package xyz.renyumeng.xkm.order.listener;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import xyz.renyumeng.xkm.model.order.OrderInfo;
import xyz.renyumeng.xkm.order.service.UserOrderService;

import javax.annotation.Resource;

import static xyz.renyumeng.xkm.rabbitMQ.RabbitMqConstant.*;
import static xyz.renyumeng.xkm.redis.RedisConstants.LOCK_SHOP_KEY;
import static xyz.renyumeng.xkm.redis.RedisConstants.QUEUE_ORDER_KEY;

/**
 * @author renyumeng
 * @date Created in 22:17 2023/7/6
 */
@Slf4j
@Component
public class ProductDeadLetterListener {
    @Resource
    private UserOrderService userOrderService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @RabbitListener(
            queues = DEAD_LETTER_PRODUCT_QUEUE
    )
    public void productListener(OrderInfo orderInfo) {
        Long orderId = orderInfo.getId();
        log.info("当前时间:{},订单id为:{}", System.currentTimeMillis(), orderId);
        OrderInfo orderInfoDb = userOrderService.getById(orderId);
        if (!ObjectUtil.isEmpty(orderInfoDb)) {
            log.info("用户{}完成对{}的支付", orderInfo.getPurchaseUserId(), orderId);
            // 删除redis的订单信息
            String queueOrderKey = QUEUE_ORDER_KEY + orderInfo.getPurchaseUserId().toString() + ":" + orderId;
            stringRedisTemplate.delete(queueOrderKey);
            return;
        }
        // 重新上架商品
        log.info("用户未完成对订单{}的支付", orderId);
        rabbitTemplate.convertAndSend(PRODUCT_EXCHANGE, PRODUCT_LIST_ROUTING_KEY, orderInfo);
        // 删除redis的订单信息
        String queueOrderKey = QUEUE_ORDER_KEY + orderInfo.getPurchaseUserId().toString() + ":" + orderId;
        stringRedisTemplate.delete(queueOrderKey);
        // 松开锁
        String lockKey = LOCK_SHOP_KEY + orderInfo.getProductId();
        stringRedisTemplate.delete(lockKey);

    }

}
